<?php
/*
Plugin Name: WP-prettyPhoto
Plugin URI: http://blog.fusi0n.org/category/wp-prettyphoto
Description: WP-prettyPhoto allows you to use <a href="http://www.no-margin-for-errors.com/projects/prettyPhoto/" alt="prettyPhoto">prettyPhoto</a> by <a href="http://www.no-margin-for-errors.com/">Stéphane Caron</a>, a jQuery-powered Lightbox clone with WordPress.
Version: 1.2.1.1
Author: Pier-Luc Petitclerc
Author URI: http://blog.fusi0n.org
Text Domain: wp-prettyphoto
*/


if (!class_exists('WP_prettyPhoto')) {
  if (!defined('WP_CONTENT_URL')) { define('WP_CONTENT_URL', get_option('wpurl').'/wp-content'); }
  if (!defined('WP_CONTENT_DIR')) { define('WP_CONTENT_DIR', ABSPATH.'wp-content'); }
  if (!defined('PRETTYPHOTO_VER')) { define('PRETTYPHOTO_VER', '2.3'); }
  if (!defined('WPPP_PATH')) { define('WPPP_PATH', WP_CONTENT_DIR.'/plugins/'.plugin_basename(dirname(__FILE__).'/')); }
  if (!defined('WPPP_URL')) { define('WPPP_URL',  WP_CONTENT_URL.'/plugins/'.plugin_basename(dirname(__FILE__))); }

  class WP_prettyPhoto {

    /**
     * Class constructor
     * Sets default options, add filters and options page.
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @param null
     * @return void
     * @since 1.2
     * @access public
    */
    public function __construct() {
      // Default values
      add_option('wppp_automate', 1);
      add_option('wppp_rel', 'prettyPhoto');
      add_option('wppp_speed', 'normal');
      add_option('wppp_padding', 40);
      add_option('wppp_opacity', 0.35);
      add_option('wppp_title', 'true');
      add_option('wppp_resize', 'true');
      add_option('wppp_counterlabel', '/');
      add_option('wppp_theme', 'dark_rounded');
      add_option('wppp_jsreplace', 1);
      add_option('wppp_media', 1);

      
      if (!is_admin() && !$this->is_mobile()) {
        if (get_option('wppp_jsreplace') == 1) {
          // jQuery - removing to make sure we're using 1.3.2
          wp_deregister_script('jquery');
          wp_register_script('jquery', WPPP_URL.'/js/jquery-1.3.2.min.js', false, '1.3.2');
          wp_enqueue_script('jquery');
        }

        // prettyPhoto JavaScript
        wp_register_script('prettyphoto', WPPP_URL.'/js/jquery.prettyPhoto.js', array('jquery'), PRETTYPHOTO_VER);
        wp_enqueue_script('prettyphoto');
        // prettyPhoto CSS
        wp_enqueue_style('prettyphoto', WPPP_URL.'/css/prettyPhoto.css', false, PRETTYPHOTO_VER);

        // Enable PNG transparency hook if we're running with IE6
        if ((strpos($wppp_theme, 'dark_') !== false) && ($this->is_ie6())) {
          wp_register_script('belatedpng', WPPP_URL.'/js/DD_belatedPNG_0.0.7a-min.js', array('prettyphoto'), '0.0.7a');
          wp_enqueue_script('belatedpng');
        }
      }
      if (is_admin()) {
        $currentLocale = get_locale();
        if (!empty($currentLocale)) {
          $moFile = WPPP_PATH.'lang/wp-prettyphoto-'.$currentLocale.".mo";
          if (@file_exists($moFile) && is_readable($moFile)) { load_plugin_textdomain('wp-prettyphoto', $moFile); }
        }
      }
      add_action('wp_head', array(&$this, 'wppp_styles'));
      add_action('admin_head', array(&$this, 'wppp_add_options_page'));
      
      if ((get_option('wppp_automate') == 1) && (!$this->is_mobile())) {
        add_filter('the_content', array(&$this, 'wppp_content_hook'), 99, 1);
        add_filter('the_excerpt', array(&$this, 'wppp_content_hook'), 99, 1);
      }
    }

    /**
     * Adds a 'Settings' link to the plugins row
     * @param array $links List of plugins to be displayed in the page
     * @param string $file Filename of the plugin currently being parsed/displayed
     * @return array Same thing as $links, but with our Settings link with it.
     * @example add_action('admin_head', 'wppp_add_options_page');
     * @author Joost de Valk
     * @link http://yoast.com/wordpress/enhanced-wordpress-contact-form/
     * @since 1.0
     * @access private
    */
    private function wppp_admin_hook($links, $file) {
      static $this_plugin;
      if (!$this_plugin) { $this_plugin = plugin_basename(__FILE__); }
      if ($file == $this_plugin) {
        $settings_link = '<a href="options-general.php?page='.plugin_basename(dirname(__FILE__)).'/wpppopt.php">' . __('Settings') . '</a>';
        array_unshift($links, $settings_link); // before other links
      }
      return $links;
    }
  
    /**
     * Adds the plugin's option page in the 'Settings' menu of the Admin
     * @param null
     * @return void
     * @author Rupert Morris
     * @since 1.0
     * @access private
    */
    private function wppp_add_options_page() {
      add_options_page('WP-prettyPhoto Options', 'WP-prettyPhoto', 'manage_options', WPPP_PATH.'wpppopt.php');
      add_filter( 'plugin_action_links', array(&$this,'wppp_admin_hook'), 10, 2 );
    }

    /**
     * Replaces occurences of $wppp_rel with the prettyPhoto rel hook
     * @param string $content Post/page contents
     * @return string Prettified post/page contents
     * @author Rupert Morris
     * @author Tanin "Regular Expression God"
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @since 1.0
     * @link http://0xtc.com/2008/05/27/auto-lightbox-function.xhtml
     * @access private
    */
    private function wppp_content_hook($content) {
      $wppp_rel         = get_option('wppp_rel');
      $fileTypes        = (get_option('wppp_media') == 1)? "\.bmp|\.gif|\.jpg|\.jpeg|\.png|\.swf|\.mov" : "\.bmp|\.gif|\.jpg|\.jpeg|\.png";
      $pattern          = array("/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)>/i",
                                "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)(rel=('|\")$wppp_rel(.*?)('|\"))([ \t\r\n\v\f]*?)((rel=('|\")$wppp_rel(.*?)('|\"))?)([ \t\r\n\v\f]?)([^\>]*?)>/i");
      return preg_replace_callback($pattern, array(&$this,'regexCallback'), $content);
    }

    /**
     * Callback function used to detect whether a string contains a link to a _blank target
     * @param array $matches Regular Expression matches from preg_replace()
     * @return bool True if _blank was found in matches, false if it wasn't
     * @global object $post
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @see wppp_content_hook
     * @since 1.2.1
     * @access private
    */
    private function regexCallback($matches) {
      global $post;
      $wppp_rel       = get_option('wppp_rel');
      $pattern        = array("/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)>/i",
                              "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)(rel=('|\")$wppp_rel(.*?)('|\"))([ \t\r\n\v\f]*?)((rel=('|\")$wppp_rel(.*?)('|\"))?)([ \t\r\n\v\f]?)([^\>]*?)>/i");
      $replacement    = array("<a$1href=$2$3$4$5$6 rel=\"{$wppp_rel}[g{$post->ID}]\">",
                              '<a$1href=$2$3$4$5$6$7>');
      return !strpos($matches['0'], '_blank')? preg_replace($pattern,$replacement,$matches['0']) : $matches['0'];
    }

    /**
     * Adds prettyPhoto in the page that is being viewed
     * @param null
     * @return void
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @example add_action('wp_head', 'wppp_styles');
     * @link http://www.no-margin-for-errors.com/projects/prettyPhoto/#howtouse
     * @since 1.0
     * @access private
    */
    private function wppp_styles() {
      $wppp_rel           = get_option('wppp_rel');
      $wppp_speed         = get_option('wppp_speed');
      $wppp_padding       = get_option('wppp_padding');
      $wppp_opacity       = get_option('wppp_opacity');
      $wppp_title         = get_option('wppp_title') == 'true'? 'true' : 'false';
      $wppp_resize        = get_option('wppp_resize') == 'true'? 'true' : 'false';
      $wppp_counterlabel  = get_option('wppp_counterlabel');
      $wppp_theme         = get_option('wppp_theme');

      $ie6 = <<<EOHEAD
        <!--[if IE 6]>
            <script>
                    DD_belatedPNG.fix('div.pictureHolder .top .left,div.pictureHolder .top .right,div.pictureHolder .top .left,div.pictureHolder .bottom .left,div.pictureHolder .bottom .right,div.pictureHolder .content a.close,div.pictureHolder .content .details .nav a.arrow_next,div.pictureHolder .content .details .nav a.arrow_previous,div.pictureHolder .content,div.pictureHolder .bottom .middle,div.pictureHolder .top .middle'); 
            </script>
        <![endif]-->
EOHEAD;

      $output = <<<EOHTML

        <script type="text/javascript" charset="utf-8">
          $(document).ready(function(){
            $("a[rel^='{$wppp_rel}']").prettyPhoto({
              animationSpeed: '{$wppp_speed}', /* fast/slow/normal */
              padding: {$wppp_padding}, /* padding for each side of the picture */
              opacity: {$wppp_opacity}, /* Value betwee 0 and 1 */
              showTitle: {$wppp_title}, /* true/false */
              allowresize: {$wppp_resize}, /* true/false */
              counter_separator_label: '{$wppp_counterlabel}', /* The separator for the gallery counter 1 "of" 2 */
              theme: '{$wppp_theme}' /* light_rounded / dark_rounded / dark_square */
            });
          });
        </script>
EOHTML;
      echo ((strpos($wppp_theme, 'dark_') !== false) && ($this->is_ie6()))? $ie6.$output : $output;;
    }

    /**
     * Fetches a list of installed prettyPhoto themes
     * @param null
     * @return array Numeric array containing directory names of installed themes
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @since 1.1
     * @static
     * @access public
    */
    static public function wppp_get_themes() {
      $themes = array();
      $dir = scandir(WPPP_PATH.'images/prettyPhoto');
      foreach ($dir as $key=>$dirname) {
        if ((strlen($dirname) > 2) && is_dir(WPPP_PATH.'images/prettyPhoto/'.$dirname)) { $themes[] = $dirname; }
      }
      return $themes;
    }

    /**
     * Detects if user is using Microsoft Internet Explorer 6
     * @param null
     * @return bool True if user is using MSIE6, False if he is not
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @since 1.1
    */
    private function is_ie6() {
      return strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false? true : false;
    }

    /**
     * Detects if user is using a known mobile browser
     * @param null
     * @return bool True if user is using a mobile browser, false if he is not
     * @author Pier-Luc Petitclerc <pL@fusi0n.org>
     * @link http://detectmobilebrowsers.mobi
     * @since 1.1
    */
    private function is_mobile() {
      $browsers = array('ipod', 'iphone', 'android', 'opera mini', 'blackberry');
      $regex = '('.implode($browsers, ')|(').')';
      return ((eregi($regex, $_SERVER['HTTP_USER_AGENT'])) || 
          (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|pda|psp|treo)/i',$_SERVER['HTTP_USER_AGENT'])) || 
          ((strpos($_SERVER['HTTP_ACCEPT'],'text/vnd.wap.wml') !== false) || (strpos($_SERVER['HTTP_ACCEPT'],'application/vnd.wap.xhtml+xml') !== false)) || 
          (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']))) ? true : false;
    }
  }

  // Fire in the hole!
  $wppp = new WP_prettyPhoto();
}
?>
